// components/ImageUpload/ImageUpload.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    image: '',
    count: {
      type: Number,
      value: 1
    },
    catalogId: {
      type: String,
      value: getApp().constant.CATALOG_UNKNOW
    },
    remove: {
      type: Boolean,
      value: true
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    uploadFile: [],
    imageList: []
  },
  created() {
    this.recombinationImageUrls()
  },
  observers: {
    'image': function (val) {
      if (val) {
        this.setData({
          uploadFile: val.split(',')
        })
        var imageList = []
        this.data.uploadFile.forEach(item => {
          imageList.push({
            url: getApp().util.getFileView(item),
            isImage: true,
            uuid: item
          })
        })
        this.setData({
          imageList
        })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    recombinationImageUrls() {
      var imageList = []
      var uploadFile = this.data.uploadFile
      this.data.uploadFile.forEach(item => {
        imageList.push({
          url: getApp().util.getFileView(item),
          uuid: item
        })
      })
      this.setData({
        imageList
      })
      this.triggerEvent('getimage', uploadFile.join(','))
    },
    removeImage({
      detail
    }) {
      var {
        file: {
          uuid
        }
      } = detail
      var uploadFile = this.data.uploadFile
      var temp = uploadFile.filter(item => {
        return item !== uuid
      })
      this.setData({
        uploadFile: temp
      })
      this.recombinationImageUrls()
    },
    handleUpload(event) {
      const {
        file
      } = event.detail;
      getApp().network.upload(getApp().api.fileUpload, {
        file: file.url,
        catalogId: this.properties.catalogId
      }).then((res) => {
        var uploadFile = this.data.uploadFile
        uploadFile.push(res.uuid)
        this.setData({
          uploadFile: uploadFile
        })
        this.recombinationImageUrls()

      }).catch((_) => {})
    },
  }
})